package com.example.makotoshoda.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * Created by makoto.shoda on 2014/12/29.
 */
public class MyDB extends SQLiteOpenHelper {
    public MyDB(Context context) {
        super(context, "MyCounter", null, 1);

    }
    public void deleteUsers() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete("users", null, null);
        db.close();

    }
    public List<ContentValues> users() {
        return select("select * from users", null);
    }
    public List<ContentValues> getUser(String name) {
        List<ContentValues> ret = select("select * from users where name = ?", new String[]{name});
        return ret;
    }
    public List<ContentValues> getUser(int id) {
        List<ContentValues> ret = select("select * from users where id = ?", new String[]{String.valueOf(id)});
        return ret;
    }


    public void saveUser(final String name, final int counter, int sort, int id) {
        List<ContentValues> users = users();

        SQLiteDatabase db = this.getWritableDatabase();
        if (id == 0) {
            db.execSQL("insert into users (name, counter, sort) values (?, ?, ?)",
                    new Object[] {name, new Integer(counter), new Integer(sort)});
        } else {
            db.execSQL("update users set name = ?, counter = ?, sort = ? where id = ?",
                    new Object[] {name, new Integer(counter), new Integer(sort), new Integer(id)});
        }

        db.close();
    }
    public void deleteUser(int id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("delete from users where id = ? ",
                new Object[] {new Integer(id)});
        db.close();
    }

    private List<ContentValues> select(String sql, String[] args) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(sql, args);
        List<ContentValues> cv = new ArrayList<ContentValues>();
        if (c.getCount() > 0) {
            c.moveToFirst();
            do {
                ContentValues value = new ContentValues();
                DatabaseUtils.cursorRowToContentValues(c, value);
                cv.add(value);
            } while (c.moveToNext());
        }
        db.close();
        return cv;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table users (id integer primary key autoincrement, name text, sort integer, counter integer);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}
